package org.wattdepot.gdata.kukuicup.updater;

import java.util.ArrayList;
import java.util.List;
import org.wattdepot.gdata.kukuicup.service.GDataService;
import org.wattdepot.gdata.kukuicup.service.GDataView;

/**
 * Enables clients to obtain a read-only view of the last thirty days spreadsheet for 
 * the August, 2011 beta evaluation.
 * @author Philip Johnson
 */
public class LastThirtyDaysViewBetaEval {
  
  /** The GDataService for this run. */
  private GDataService gdataService;
  /** The abstraction violation.  This class must know the spreadsheet name. */
  private String lastThirtyDaysSpreadsheetName = "EnergyLastThirtyDaysBetaEval";
  /** The cached view of the last thirty days beta eval spreadsheet. */
  private GDataView lastThirtyDaysView = null;

  /**
   * Creates a new LastThirtyDaysView given the service. 
   * @param gdataService The service. 
   */
  public LastThirtyDaysViewBetaEval(GDataService gdataService) {
    this.gdataService = gdataService;
  }
  
  /**
   * Return a view of the last thirty days beta eval spreadsheet.
   * @return The last thirty days beta eval spreadsheet.
   * @throws RuntimeException If this can't be done. 
   */
  private GDataView getLastThirtyDaysView() {
    if (lastThirtyDaysView != null) {
      return lastThirtyDaysView;
    }
    // Otherwise get the view and cache it.
    try { 
      lastThirtyDaysView = new GDataView(this.gdataService, 
        this.gdataService.getSpreadsheetURL(this.lastThirtyDaysSpreadsheetName));
      return lastThirtyDaysView;
    }
    catch (Exception e) {
      throw new RuntimeException("Couldn't get" + this.lastThirtyDaysSpreadsheetName, e);
    }
  }
  
  /**
   * Returns a list of the thirty days of energy data for the given source.
   * @param sourceName The source whose baselines we're interested in.
   * @return The list of energy consumption data for the thirty days, from most recent to oldest.
   */
  public List<Integer> getEnergyHistory(String sourceName) {
    GDataView view = getLastThirtyDaysView();
    int row = view.findRow(sourceName); 
    List<String> rowData = view.getCellData(view.getRow(row));
    List<Integer> energyList = new ArrayList<Integer>();
    int startColumn = 2;
    // Get thirty days of data.
    for (int i = 0; i < 30; i++) {
      energyList.add(Integer.valueOf(rowData.get(i + startColumn)));
    }
    return energyList;
  }
}
